package com.fly.core.utils;

import org.junit.jupiter.api.Test;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;

/**
 * 
 * 雪花算法生成全局唯一ID
 * 
 * @author 00fly
 * @version [版本号, 2023年3月27日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class SnowFlakeUtil
{
    private static long workerId = 0L;
    
    private static long datacenterId = 1L;
    
    private static Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);
    
    static
    {
        try
        {
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
        }
        catch (Exception e)
        {
            workerId = NetUtil.getLocalhostStr().hashCode();
        }
    }
    
    public synchronized static long snowflakeId(long workerId, long datacenterId)
    {
        Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);
        return snowflake.nextId();
    }
    
    public synchronized static long snowflakeId()
    {
        return snowflake.nextId();
    }
    
    public synchronized static String snowflakeStrId()
    {
        return String.valueOf(snowflake.nextId());
    }
    
    @Test
    public void test()
    {
        System.out.println(snowflakeStrId());
    }
}
